const inquirer = require('inquirer');
const shelljs = require('shelljs');
const fs = require('fs');
const path = require('path');
const _options = {
    prefix: 'RWH-',
    splitChar: ' ',
    needPush: true,
    taskSystem: ''
};
/**
 * git提交
 * @param {*} message 提交信息
 */
const commit = message => {
    shelljs.exec('git add .');
    shelljs.exec(`git commit -m "${message}"`);
    if (!_options.needPush) {
        console.log('\x1B[36m%s\x1B[0m', 'commit success!')
        process.exit(0);
    }
    shelljs.exec('git pull');
    if (shelljs.exec('git status').code === 0) {
        shelljs.exec('git push');
    };
};

/**
 * 确认提交信息
 * @param {*} message 提交信息
 */
const confirmCommitInfo = message => {
    inquirer.prompt([{
        type: 'confirm',
        message: `提交信息为"${message}",是否需要提交？`,
        name: 'watch'
    }]).then(answer => {
        if (answer.watch) {
            commit(message);
        }
        process.exit(0);
    })
}

/**
 * 获取配置文件
 * @param {*} _path 文件路径
 * @returns 
 */
const getConfig = _path => {
    if (fs.existsSync(_path)) {
        return fs.readFileSync(_path, 'utf-8');
    } else {
        console.error('tab-commit.json is not found!');
    }
}

const run = () => {
    inquirer.prompt([{
        type: 'input',
        name: 'task',
        message: '任务号',
        default: ''
    }, {
        type: 'list',
        name: 'action',
        message: '提交类型',
        default: 'feat',
        choices: [{
            name: 'feat: 增加新功能',
            value: 'feat'
        }, {
            name: 'fix: 修复bug',
            value: 'fix'
        }, {
            name: 'perf: 提高性能的改动',
            value: 'perf'
        }, {
            name: 'refactor: 代码重构',
            value: 'refactor'
        }, {
            value: 'revert',
            name: 'revert: 撤销之前的commit'
        }, {
            value: 'style',
            name: 'style: 代码格式修改'
        }, {
            value: 'docs',
            name: 'docs: 修改文档相关内容'
        }, {
            value: 'test',
            name: 'test: 测试相关内容'
        }, {
            value: 'ci',
            name: 'ci: ci相关修改'
        }, {
            value: 'build',
            name: 'build: 依赖改动'
        }, {
            value: 'chore',
            name: 'chore: 其他改动'
        }]
    }, {
        type: 'input',
        name: 'messgae',
        message: '提交信息',
        default: ''
    }]).then(answer => {
        const messageArray = [];
        const {
            prefix,
            splitChar,
            taskSystem
        } = _options;
        for (const key in answer) {
            if (key === 'task') {
                messageArray.push(`${prefix}${answer[key]}`);
            } else if (key === 'messgae') {
                const taskContent = taskSystem ? `${taskSystem}\n` : '';
                messageArray.push(`${taskContent}${answer[key]}`);
            } else {
                messageArray.push(answer[key]);
            }
        }
        const message = messageArray.join(splitChar);

        confirmCommitInfo(message);
    });
}

// init
const init = () => {
    const argv = process.argv;
    const isCustom = argv.includes('-c');

    if (isCustom) {
        const index = argv.findIndex(arg => arg === '-c');
        // 项目根目录
        const rootPath = __dirname.split('node_modules')[0];
        const customConfigPath = path.resolve(rootPath, argv[index + 1]);
        // 获取自定义配置
        let customConfig = getConfig(customConfigPath);
        customConfig = JSON.parse(customConfig);
        Object.assign(_options, customConfig);
    }

    run();
}


init();